<?php

/**
 * Framework_Module_CP_Setting
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Modules
 * @filesource
 */

/**
 * Framework_Module_CP_Setting
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Modules
 */
class Framework_Module_CP_Settings extends Framework_Module_CP
{

	/**
	 * __construct
	 *
	 * Initializes the module: sets the default presenter, the allowed
	 * conrollers, and the allowed events
	 *
	 * @access 		public
	 * @return 		void
	 */
	public function __construct()
	{
		parent::__construct();
		$this->tplFile = 'Settings.tpl';
	}

	/**
	 * __default
	 *
	 * Generates settings forms
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function __default()
	{
			
		// Password settings form
		$this->forms['settingsPassword'] = Framework_Quickform::factory('settingsPassword', 'post', Framework::$request->getBaseHTTPPath().'/'.$this->owner->loginName.'/CP/Settings',null,null,true);
			
		$this->forms['settingsPassword']->addElement('password','oldPassword','Current Password', 'class="textInput" id="oldPassword"');
		$this->forms['settingsPassword']->registerRule('passwordCheck','function','passwordCheck',$this);
			
		$this->forms['settingsPassword']->addElement('password','newPassword','New Password', 'class="textInput" id="newPassword"');
		$this->forms['settingsPassword']->addRule('newPassword', 'Your password must be between 4 and 8 chars', 'rangelength', array(4,8));
		$this->forms['settingsPassword']->addRule('newPassword', 'Required', 'required');
			
		$this->forms['settingsPassword']->addElement('password','newPassword2','Repeat New Password', 'class="textInput" id="newPassword2"');
		$this->forms['settingsPassword']->addRule('newPassword2', 'Required', 'required');
			
		$this->forms['settingsPassword']->addRule(array('newPassword', 'newPassword2'), 'The passwords do not match', 'compare', null);

		$this->forms['settingsPassword']->addElement('submit','btnSubmitPassword','Update Password','class="button" id="btnSubmitPassword"');
			
		$this->forms['settingsPassword']->applyFilter('__ALL__','trim');

		// Process password change form
		if ($this->forms['settingsPassword']->validate()) {
			$result = $this->forms['settingsPassword']->process(array($this, 'processPassword'));
		}

		// Module settings form
		$this->forms['settingsModule'] = Framework_Quickform::factory('settingsModule', 'post', Framework::$request->getBaseHTTPPath().'/'.$this->owner->loginName.'/CP/Settings' ,null,null,true);

		$meta = Framework_Meta::factory();

		$table = $meta->getTable();

		$queryArray = array(
		'sqlKey' => array(
		'select' => 'idMetaModule, moduleAlias',
		'where'  => 'moduleActive = 1 AND moduleCategory = "User" AND idMetaModule NOT IN("CP")',
		'get'    => 'assoc'
			)
		);

		$modules = $table->select($queryArray);

		$this->forms['settingsModule']->addElement('select','defaultModule','Default Module: ', $modules, 'class="selectInput" id="defaultModule"');
		// Set Defaults
		if ($this->owner->defaultModule)
		$this->forms['settingsModule']->setDefaults(array('defaultModule'=>$this->owner->defaultModule));
		else
		$this->forms['settingsModule']->setDefaults(array('defaultModule'=>'Profile'));

		$this->forms['settingsModule']->addElement('submit','btnSubmitModule','Set Default Module','class="button" id="btnSubmitModule"');
			
			
			
		// Process default module form
		if ($this->forms['settingsModule']->validate()) {
			$result = $this->forms['settingsModule']->process(array($this, 'processModule'));
		}
			
			
		// SiteUser data form (avatar and blurb)
		if(strlen($this->owner->avatarURL)) {
			$this->setData('avatar',$this->owner->avatarURL);
		}

		$this->forms['settingsBasic'] = Framework_Quickform::factory('settingsBasic', 'post',  Framework::$request->getBaseHTTPPath().'/'.$this->owner->loginName.'/CP/Settings', null, null, true);
		$this->forms['settingsBasic']->addElement('textarea','blurb','Blurb: ','class="textInput" id="blurb"');
		$this->forms['settingsBasic']->setDefaults(array('blurb'=>$this->owner->blurb));

			
		$this->forms['settingsBasic']->addElement('file', 'avatarFile', 'Upload Avatar:');
		$this->forms['settingsBasic']->addRule('avatarFile', 'Cannot exceed 50KB', 'maxfilesize', 51200);
		$this->forms['settingsBasic']->addRule('avatarFile', 'Must be a JPEG or GIF', 'mimetype', array('image/jpeg','image/jpg','image/gif','image/pjpeg'));
			
		$this->forms['settingsBasic']->addElement('text','imgURI','Select external image: ', 'class="textInput" id="imgURI"');
		$this->forms['settingsBasic']->addRule('imgURI','Must be in correct format','regex','/^http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/i');
			
		// Submit button
		$this->forms['settingsBasic']->addElement('submit','btnSubmit','Update','class="button" id="updateButton"');

		// Filters
		$this->forms['settingsBasic']->applyFilter('__ALL__','trim');
		$this->forms['settingsBasic']->applyFilter('__ALL__','htmlentities');

		// Process form
		if ($this->forms['settingsBasic']->validate()) {
			$result = $this->forms['settingsBasic']->process(array($this, 'processBasicDetails'),true);
		}


	}

	/**
	 * processBasicDetails
	 *
	 *
	 * @access 		public
	 * @param 		array		$data		Data to process
	 * @return 		boolean		true
	 */
	public function processBasicDetails($data)
	{
			
		// Blurb
		$blurb = substr($data['blurb'], 0, 350);

		// Process file
		$file = $this->forms['settingsBasic']->getElement('avatarFile');
		if ($file->isUploadedFile()) {
			$fileManager = new Framework_File($this->owner);
			$fileManager->removeFile('avatar',$this->owner->userName);
			$result = $fileManager->addFileUpload($file,'avatar',$this->owner->userName);
			if (PEAR::isError($result)){
				$errors[] = 'Could Not Upload Image: '.$result->getMessage();
			} else {
				$avatarURL = $result['httpPath'];
				$this->owner->avatarURL = $avatarURL;
				$update = array(
					'avatarURL' => $avatarURL,
					'blurb' => $blurb,
				);
				$result = $this->owner->update('SiteUser', $update, 'idSiteUser = '.$this->owner->idSiteUser);
				if (PEAR::isError($result))
					$errors[] = 'Database Error: Could not update avatar URL-'.$result->getMessage();
			}

		} elseif (strlen($data['imgURI'])) {
			$avatarURL = $data['imgURI'];
			$update = array(
				'avatarURL' => $avatarURL,
				'blurb' => $blurb,
			);

			$result = $this->owner->update('SiteUser', $update, 'idSiteUser = '.$this->owner->idSiteUser);
			
			if (PEAR::isError($result))
				$errors[] = 'Database Error: Could not update avatar URL-'.$result->getMessage();
		} else {
			$update = array(
				'blurb' => $blurb,
			);
			$result = $this->owner->update('SiteUser', $update, 'idSiteUser = '.$this->owner->idSiteUser);

			if (PEAR::isError($result))
				$errors[] = 'Database Error: Could not update avatar URL-'.$result->getMessage();
		}


			
		if ($errors) {
			$this->setData('errors',$errors);
			$this->setData('formResponse','There are Errors:');
		} else {
			$this->setData('formResponse','Profile Update Success!');
		}
			

		return true;
	}

	/**
	 * processModule
	 *
	 *
	 * @access 		public
	 * @param 		array		$data		Data to process
	 * @return 		boolean		true
	 */
	public function processModule($data)
	{
		$this->owner->defaultModule = $data['defaultModule'];
		$result = $this->owner->save();
		if(!PEAR::isError($result))
		$this->setData('formResponse','Default module changed');
		else
		$this->setData('formResponse','Error: Cannot change default module: '.$result->getMessage());
			
		return true;
	}

	/**
	 * processPassword
	 *
	 *
	 * @access 		public
	 * @param 		array		$data		Data to process
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function processPassword($data)
	{
			
		$this->owner->pWord = md5($data['newPassword']);
		$result = $this->owner->save();
		if(!PEAR::isError($result))
		$this->setData('formResponse','Password Changed');
		else
		$this->setData('formResponse','Database Error: Cannot change password: '.$result->getMessage());
			
		return true;

	}

	/**
	 * passwordCheck
	 *
	 *
	 * @access 		public
	 * @param 		string		$value		Password to check
	 * @return 		boolean
	 */
	public function passwordCheck($value)
	{
		if($this->owner->pWord == md5($value))
		return true;
		else
		return false;
	}
}



?>